﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using DeenGames.Utils;
using Redbrick.Silverlight.Common;
using Redbrick.Silverlight.UI;
using Redbrick.Silverlight;
using Moria.Common.Model;
using Moria.Common;

namespace Moria.Silverlight.Controls
{
    public partial class LoadGameDialog : ChildWindow
    {

        public static readonly DependencyProperty ItemDoubleClickCommandProperty = DependencyProperty.Register("ItemDoubleClickCommand", typeof(ICommand), typeof(LoadGameDialog), new PropertyMetadata(null));

        public LoadGameDialog()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(LoadGameDialog_Loaded);
        }

        void LoadGameDialog_Loaded(object sender, RoutedEventArgs e)
        {
            List<string> saveGames = new List<string>();
            this.Moria.FileList.ForEach(s => saveGames.Add(s.Split(TheGame.SaveGameSeperatorToken).First()));
            lbSavedGames.ItemsSource = saveGames;

            DelegateCommand dc = new DelegateCommand();
            dc.Executed += new EventHandler<CommandArgs>(DoubleClick_Executed);
            dc.CanExecuteHandler = (o) => saveGames.Count > 0;
            this.ItemDoubleClickCommand = dc;
        }
        
        void DoubleClick_Executed(object sender, CommandArgs e)
        {
            this.SaveFileName = this.Moria.FileList.FirstOrDefault(s => s.StartsWith(lbSavedGames.SelectedItem.ToString()));
            this.SaveFileName = SaveFileName.Split(TheGame.SaveGameSeperatorToken).First();
            this.DialogResult = true;
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            this.SaveFileName = this.Moria.FileList.FirstOrDefault(s => s.StartsWith(lbSavedGames.SelectedItem.ToString()));
            this.SaveFileName = SaveFileName.Split(TheGame.SaveGameSeperatorToken).First();
            this.DialogResult = true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.OKButton.IsEnabled = lbSavedGames.SelectedIndex != -1;
        }
        public TheGame Moria { get { return this.DataContext as TheGame; } }
        public string SaveFileName { get; private set; }
        public ICommand ItemDoubleClickCommand
        {
            get { return (ICommand)GetValue(ItemDoubleClickCommandProperty); }
            set { SetValue(ItemDoubleClickCommandProperty, value); }
        }
    }
}

